package com.chen.servicedriveruser.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.chen.internalcommon.dto.Car;
import com.chen.internalcommon.dto.ResponseResult;
import com.chen.internalcommon.response.TrackResponse;
import com.chen.servicedriveruser.mapper.CarMapper;
import com.chen.servicedriveruser.remote.ServiceMapClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author chenLiuPing
 **/
@Service
@Slf4j
public class CarService {

    @Autowired
    private ServiceMapClient serviceMapClient;

    @Autowired
    private CarMapper carMapper;
    public ResponseResult addCar(Car car) {
        try {
            long id = IdWorker.getId(car);
            car.setId(id);
            String tid = serviceMapClient.addTerminal(car.getVehicleNo(), car.getId().toString()).getData().getTid();
            log.info("创建车辆终端：{}", tid);
            TrackResponse trackResponse = serviceMapClient.addTrack(tid).getData();
            String trid = trackResponse.getTrid();
            String trname = trackResponse.getTrname();
            log.info("创建车辆轨迹：{}", trid);
            car.setTid(tid);
            car.setTrid(trid);
            car.setTrname(trname);

            carMapper.insert(car);
            log.info("完成车辆信息的插入");
        } catch (Exception e) {
            return ResponseResult.fail(e.getMessage());
        }
        return ResponseResult.success();
    }

    public ResponseResult getCarById(Long carId) {
        LambdaQueryWrapper<Car> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Car::getId, carId);
        Car car = carMapper.selectOne(queryWrapper);
        log.info("根据carId{}查询到的car{}", carId, car);
        return ResponseResult.success(car);
    }
}
